import React, { useState, useCallback, useEffect } from 'react';
import {
    Button,
    IconButton,
    Tooltip,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Typography,
    Box,
    Paper,
    CircularProgress,
    Alert,
    Switch,
    FormControlLabel,
    Snackbar
} from '@mui/material';
import {
    FolderOpen,
    Save,
    SyncAlt,
    Close,
    AutoAwesome
} from '@mui/icons-material';
import { useFileSystem, useFileSync } from '../../hooks/fileSystem/index.ts';
import { useNovel } from '../../context/NovelContext.tsx';

/**
 * 文件选择器组件属性
 */
interface FileSelectorProps {
    buttonVariant?: 'icon' | 'text' | 'both';
    variant?: 'text' | 'outlined' | 'contained';
    label?: string;
    onFolderSelected?: (rootFolder: any) => void;
    showStatus?: boolean;
    autoImport?: boolean;
}

/**
 * 文件选择器组件
 * 提供文件夹选择和同步功能
 */
const FileSelector: React.FC<FileSelectorProps> = ({
    buttonVariant = 'icon',
    variant = 'outlined',
    label = '打开文件夹',
    onFolderSelected,
    showStatus = false,
    autoImport = true
}) => {
    const [dialogOpen, setDialogOpen] = useState(false);
    const [autoImportEnabled, setAutoImportEnabled] = useState(autoImport);
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');

    const fileSystem = useFileSystem();
    const {
        syncState,
        selectRootFolder,
        startSync,
        toggleSync,
        isSyncing,
        hasError,
        hasSyncFolder,
        autoImportFromFolder
    } = useFileSync();

    const { importFromFileSystem } = useNovel();

    // 显示导入成功消息
    const showSuccessMessage = useCallback((message: string) => {
        setSnackbarMessage(message);
        setSnackbarOpen(true);
    }, []);

    // 关闭提示消息
    const handleCloseSnackbar = useCallback(() => {
        setSnackbarOpen(false);
    }, []);

    // 打开文件夹选择对话框
    const handleOpenDialog = useCallback(() => {
        setDialogOpen(true);
    }, []);

    // 关闭对话框
    const handleCloseDialog = useCallback(() => {
        setDialogOpen(false);
    }, []);

    // 选择文件夹
    const handleSelectFolder = useCallback(async () => {
        try {
            const folderResult = await selectRootFolder();
            if (folderResult && folderResult.folder) {
                if (onFolderSelected) {
                    onFolderSelected(folderResult.folder);
                }

                // 自动扫描和导入文件夹结构
                if (autoImportEnabled) {
                    const importResult = await autoImportFromFolder(folderResult.folder);

                    // 如果扫描成功，立即导入到文件树
                    if (importResult?.success && importResult.novel) {
                        await importFromFileSystem(importResult.novel);
                        showSuccessMessage(`成功导入小说：${importResult.novel.name}`);
                    }
                }
            }
            setDialogOpen(false);
        } catch (error) {
            console.error('选择文件夹失败:', error);
        }
    }, [selectRootFolder, onFolderSelected, autoImportEnabled, autoImportFromFolder, importFromFileSystem, showSuccessMessage]);

    // 开始同步
    const handleSync = useCallback(() => {
        startSync();
    }, [startSync]);

    // 切换自动导入设置
    const handleToggleAutoImport = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        setAutoImportEnabled(event.target.checked);
    }, []);

    // 渲染按钮根据不同模式
    const renderButton = () => {
        switch (buttonVariant) {
            case 'text':
                return (
                    <Button
                        onClick={handleOpenDialog}
                        startIcon={<FolderOpen />}
                        size="small"
                        color="primary"
                        variant={variant}
                    >
                        {label}
                    </Button>
                );
            case 'both':
                return (
                    <Button
                        onClick={handleOpenDialog}
                        startIcon={<FolderOpen />}
                        size="small"
                        variant={variant}
                        color="primary"
                    >
                        {label}
                    </Button>
                );
            case 'icon':
            default:
                return (
                    <Tooltip title={label}>
                        <IconButton
                            onClick={handleOpenDialog}
                            size="small"
                            color="primary"
                        >
                            <FolderOpen />
                        </IconButton>
                    </Tooltip>
                );
        }
    };

    // 渲染同步状态
    const renderSyncStatus = () => {
        if (!showStatus) return null;

        return (
            <Box sx={{ display: 'flex', alignItems: 'center', ml: 1 }}>
                {isSyncing ? (
                    <CircularProgress size={16} sx={{ mr: 1 }} />
                ) : hasError ? (
                    <Alert severity="error" sx={{ py: 0, px: 1, fontSize: '0.75rem' }}>
                        同步错误
                    </Alert>
                ) : hasSyncFolder ? (
                    <Tooltip title="同步已连接">
                        <Save fontSize="small" color="success" />
                    </Tooltip>
                ) : null}

                {hasSyncFolder && !isSyncing && (
                    <Tooltip title="开始同步">
                        <IconButton onClick={handleSync} size="small">
                            <SyncAlt fontSize="small" />
                        </IconButton>
                    </Tooltip>
                )}
            </Box>
        );
    };

    return (
        <>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
                {renderButton()}
                {renderSyncStatus()}
            </Box>

            {/* 文件夹选择对话框 */}
            <Dialog open={dialogOpen} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
                <DialogTitle>
                    选择文件夹
                    <IconButton
                        aria-label="close"
                        onClick={handleCloseDialog}
                        sx={{ position: 'absolute', right: 8, top: 8 }}
                    >
                        <Close />
                    </IconButton>
                </DialogTitle>
                <DialogContent>
                    <Typography variant="body2" gutterBottom>
                        选择一个文件夹作为小说存储位置。该文件夹将用于保存小说的章节和卷。
                    </Typography>

                    <FormControlLabel
                        control={
                            <Switch
                                checked={autoImportEnabled}
                                onChange={handleToggleAutoImport}
                                color="primary"
                            />
                        }
                        label={
                            <Typography variant="body2">
                                自动导入选中文件夹的内容
                            </Typography>
                        }
                        sx={{ mt: 2, mb: 1 }}
                    />

                    {autoImportEnabled && (
                        <Alert severity="info" sx={{ mt: 1, mb: 2 }}>
                            选择文件夹后，将自动扫描并导入其结构到左侧文件树
                        </Alert>
                    )}

                    {hasSyncFolder && (
                        <Paper variant="outlined" sx={{ p: 1, mt: 1, mb: 2 }}>
                            <Typography variant="caption">
                                当前文件夹: {syncState.rootFolder?.name}
                                {syncState.rootFolder?.path && (
                                    <Box component="span" sx={{ display: 'block', fontSize: '0.7rem', color: 'text.secondary' }}>
                                        {syncState.rootFolder.path}
                                    </Box>
                                )}
                            </Typography>
                        </Paper>
                    )}
                    <Typography variant="caption" color="text.secondary">
                        注意: 在Web环境中，您需要在每次打开应用时重新选择文件夹。
                    </Typography>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleCloseDialog}>取消</Button>
                    <Button
                        onClick={handleSelectFolder}
                        variant="contained"
                        color="primary"
                        startIcon={autoImportEnabled ? <AutoAwesome /> : <FolderOpen />}
                    >
                        {autoImportEnabled ? '选择并导入' : '选择文件夹'}
                    </Button>
                </DialogActions>
            </Dialog>

            {/* 导入成功提示 */}
            <Snackbar
                open={snackbarOpen}
                autoHideDuration={3000}
                onClose={handleCloseSnackbar}
                message={snackbarMessage}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            />
        </>
    );
};

export default FileSelector; 